package main;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class PatternMatching {
	
	
	public static boolean isMatching(String pattern, String file)
	{
		String  check=null;
		if(pattern==null) return true;
		if(pattern=="")   return true;
		if(pattern.startsWith("*"))
		{
			check=pattern.substring(1);
			System.out.println("STARTSWITH CHECK = " + check);
			if(file.endsWith(check)) return true;
		}
		else if(pattern.endsWith("*"))
		{
			check=pattern.substring(0,pattern.length()-1);
			System.out.println("ENDSWITH CHECK = " + check);
			if(file.startsWith(check)) return true;
		}
		else if(pattern.contains("*"))
		{
			int pos = pattern.indexOf("*");
			System.out.println("POS = " + pos);
			check = pattern.substring(0,pos-1);
			System.out.println("CONTAINS CHECK = " + check);
			if(file.startsWith(check))
			{
				check = pattern.substring(pos+1);
				System.out.println("CHECK = " + check);
				if(file.endsWith(check)) return true;
			}
		}
		else if(file.contains(pattern)) return true;
		return false;
	}
	
	public static boolean isMatching2(String pattern, String file)
	{
		boolean match=false;
		System.out.println(pattern);
		System.out.println(file);
		//QUESTO RISOLVE IL PROBLEMA!!!!
		if(pattern==null) pattern = "*.*";
		if(pattern.contains("."))
			pattern=pattern.replace(".", "\\.");
		if(pattern.contains("*"))
			pattern=pattern.replace("*", ".*");
		
		if(pattern.contains("?"))
			pattern=pattern.replace("?", "\\S");
	
		Pattern p= Pattern.compile(pattern);
		Matcher m=p.matcher(file);
		
		if(m.matches())
		{
			match=true;
		}
		return match;
	}
} 
